
package com.openwater.core;

import java.util.HashMap;
import java.util.Map;

import android.content.res.Resources;

import com.openwater.tools.ShaderUtil;

public class ShaderManager {

    /**
     * Resource handle
     */
    private Resources r;

    private ShaderManager() {
    }

    private static ShaderManager instance = null;

    /**must invoke in GL-thread*/
    public synchronized static ShaderManager instance(Resources r) {
        if (instance == null) {
            instance = new ShaderManager();
            instance.r = r;
            instance.genShader("baseShader", "vertex_base.sh", "frag_base.sh");
        }
        return instance;
    }

    /**
     * an hash map store the shader program
     */
    private Map<String, Integer> mShaderMap = new HashMap<String, Integer>();

    public int getShader(String name) {
        return mShaderMap.get(name);
    }

    public int getBaseShader(){
        return getShader("baseShader");
    }

    /**
     * @param name key
     * @param vname vertex shader script file name
     * @param fname fragment shader script file name
     * @return
     */
    public int genShader(String name, String vname, String fname) {
        String vertexSource = ShaderUtil.getScriptFromAssets(r, vname);
        String fragmentSource = ShaderUtil.getScriptFromAssets(r, fname);
        int shader = ShaderUtil.createProgram(vertexSource, fragmentSource);
        mShaderMap.put(name, shader);
        return shader;
    }
}
